import urllib.parse
import re


def _get_real_source_url(image_url):
    try:
        image_url_ = urllib.parse.parse_qs(urllib.parse.urlparse(image_url).path)['/image_search/src']
    except Exception:
        image_url_ = [image_url]
    finally:
        assert len(image_url_) == 1
        image_url = image_url_[0]
    return image_url


_translate = str.maketrans("wkv1ju2it3hs4g5rq6fp7eo8dn9cm0bla", "abcdefghijklmnopqrstuvw1234567890")


def _parse_baidu_encoded_url(url):
    if url.startswith('http'):
        return url
    url = re.sub('AzdH3F', '/', url)
    url = re.sub("_z&e3B", ".", url)
    url = re.sub('_z2C\$q', ":", url)
    # mapping = {'_z2C$q': ':', '_z&e3B': '.', 'AzdH3F': '/'}
    # for k, v in mapping.items():
    #     url = url.replace(k, v)
    url = url.translate(_translate)
    assert url.startswith('http')
    return url


def _parse_baidu_json(response_json: dict):
    if 'data' not in response_json:
        return None
    response_json = response_json['data']
    result = []
    for image_info in response_json:
        if len(image_info) == 0:
            continue
        if image_info['adType'] != '0':
            continue
        thumbnail_url = image_info['thumbURL']
        index = thumbnail_url.find('/it/u=')
        assert index != -1
        thumbnail_short_url = thumbnail_url[index + 4: ]
        source_url = _parse_baidu_encoded_url(image_info['fromURL'])
        download_url = _parse_baidu_encoded_url(image_info['objURL'])
        source_image_url = download_url
        # source_image_url = _get_real_source_url(download_url)
        caption = image_info['fromPageTitle']
        caption = caption.replace('<strong>', '')
        caption = caption.replace('</strong>', '')
        result.append((download_url, thumbnail_url, thumbnail_short_url, source_url, source_image_url, caption))
    return result


def _get_valid_json(json_bytes: bytes):
    json_bytes = json_bytes.decode('utf-8', 'ignore').encode("utf-8")
    index = 0
    replace_indices = []
    while True:
        base64_pattern = b'"base64": \''
        base64_begin = json_bytes.find(base64_pattern, index)
        if base64_begin == -1:
            break
        replace_indices.append(base64_begin + len(base64_pattern) - 1)
        base64_begin += len(base64_pattern)
        base64_end = json_bytes.find(b'\'', base64_begin)
        if base64_end == -1:
            break
        replace_indices.append(base64_end)
        index = base64_end + 1
    if len(replace_indices) > 0:
        json_bytes = bytearray(json_bytes)
        for index in replace_indices:
            json_bytes[index: index + 1] = b'"'
        json_bytes = bytes(json_bytes)

    json_bytes = json_bytes.replace(b"\\'", b"'")
    return json_bytes
